from . import profile_blue
from info.utils.commons import login_required
from info.utils.response_code import RET
from flask import g,redirect,render_template,current_app,request,jsonify,session
from info.models import User,Category,News
from info import db
from info.utils.image_storage import storage
from info import constants


@profile_blue.route("/info")
@login_required
def user_info():
    """
    用户个人信息首页
    １　判断用户登陆，如果未登陆，返回网页首页或者登陆页面
    :return:
    """
    user=g.user
    if not user:
        return redirect('/')
    data = {
        "user":user.to_dict(),
    }

    return render_template("news/user.html", data=data)

@profile_blue.route("/base_info",methods=['GET','POST'])
@login_required
def base_info():
    """
    １　判断methods的请求方式，ｇｅｔ时为显示用户信息
    ２　ｐｏｓｔ时
    ３　获得前台发送的参数，signature,nick_name,gender
    ４　参数校验完整性，单独校验ｇｅｎｄｅｒ的值
    ５　保存用户数据到数据库
    ６　更新缓存中的nick_name
    ７　返回数据
    :return:
    """
    user = g.user
    # 如果是get请求
    if request.method == 'GET':
        data = {
            'user': user.to_dict()
        }
        return render_template('news/user_base_info.html', data=data)
    signature=request.json.get("signature")
    gender=request.json.get("gender")
    nick_name=request.json.get("nick_name")
    if not all([signature,gender,nick_name]):
        return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
    if gender not in ["MAN","WOMAN"]:
        return jsonify(errno=RET.DATAERR,errmsg="gender参数错误")
    """检查昵称是否重复，通过判断该昵称是否存在用户即可"""
    try:
        user1=User.query.filter_by(nick_name=nick_name).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="读取数据库失败")
    """如果用户不存在use的值为Ｎｏｎｅ"""
    if user1 and user1!=user:
        return jsonify(errno=RET.PARAMERR,errmsg="该昵称已经存在")
    user.nick_name=nick_name
    user.gender=gender
    user.signature=signature
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="保存数据库数据失败")
    session["nick_name"]=nick_name
    return jsonify(errno=RET.OK,errmsg="ok")


@profile_blue.route("/pic_info",methods=["GET","POST"])
@login_required
def pic_info():
    """
    '''
    １　获得参数图片，并校验图片不为空
    ２　保存图片到骑牛云
    ３　获得图片的ｕｒｌ
    ４　将图片的绝对路径传给前端
    '''
    :return:
    """
    user = g.user
    # 如果是get请求
    if request.method == 'GET':

        data = {
            'user': user.to_dict()
        }
        return render_template("news/user_pic_info.html", data=data)

    avatar=request.files.get("avatar")
    if not avatar:
        return jsonify(errnp=RET.PARAMERR,errmsg="获取图片参数错误")
    try:
        image_data=avatar.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR,errmsg="参数格式不对")
    try:
        image_name=storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg="上传图片失败")
    user.avatar_url = image_name
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR,errmsg='保存数据失败')
    image_url=constants.QINIU_DOMIN_PREFIX+ user.avatar_url
    # image_url=constants.QINIU_DOMIN_PREFIX+ image_name
    data ={
        "avatar_url":image_url
    }
    return jsonify(errno=RET.OK, errmsg='OK', data=data)

@profile_blue.route("/news_release",methods=['GET','POST'])
@login_required
def news_release():
    """
    １　ｇｅｔ时　，显示模板，加载新闻类别
    ２　ｐｏｓｔ，获取前段发过来的ｆｏｒｍ中输入的参数
    ３　校验参数
    ４
    :return:
    """
    user = g.user
    # 如果是get请求
    if request.method == 'GET':
        try:
            categories=Category.query.all()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DBERR,errmsg="读取数据库失败")
        if not categories:
            return jsonify(errno=RET.DATAERR,errmsg="无分类数据")
        category_list = []
        for category in categories:
            category_list.append(category.to_dict())
        #     print("每个类别的名称：",category)
        # print("类别对象列表",categories)
        # print("类别信息组成的列表",category_list)
        data = {
            'user': user.to_dict(),
            "categories":category_list[1:],
        }
        return render_template("news/user_news_release.html", data=data)
    # 获取参数
    title = request.form.get('title')
    category_id = request.form.get('category_id')
    digest = request.form.get('digest')
    index_image = request.files.get('index_image')
    content = request.form.get('content')
    # print(title,category_id,digest,index_image,content)
    # 校验参数的完整性
    if not all([title, category_id, digest, index_image, content]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数缺失')
    # 校验新闻分类
    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数类型错误')
    # 读取图片数据
    try:
        image_data = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='图片文件错误')
    # 调用七牛云上传新闻图片
    try:
        image_name = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='上传图片失败')
    # 构造模型类对象，存储新闻数据
    news = News()
    news.title = title
    news.category_id = category_id
    news.digest = digest
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + image_name
    news.content = content
    news.user_id = user.id
    news.source = '个人发布'
    news.status = 0
    # 提交数据到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg='保存数据失败')
    # 返回结果
    return jsonify(errno=RET.OK, errmsg='OK')
@profile_blue.route("/news_list")
@login_required
def news_list():
    """
    个人中心的新闻列表
    :return:
    """
    user = g.user
    # 如果是get请求
    # 当第一次点击用户列表时，前端并没有串ｐ的值过来，所以必须设置默认值
    p=request.args.get("p",1)

    try:
        p = int(p)
    except Exception as e:
        print("p出现了异常")
        current_app.logger.error(e)
        p = 1

    try:
        paginate = News.query.filter(News.user_id==user.id).order_by(News.create_time.desc()).paginate(p, 3, False)
        # news=News.query.filter(News.user_id==user.id).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="数据库读取新闻失败")
    if not paginate:
        return jsonify(errno=RET.DATAERR,errmsg="该用户还没有发布过新闻")
    total_page = paginate.pages
    current_page = paginate.page
    news_list = paginate.items
    news_dict_list = []

    for news in news_list:
        '''注意news.to_dict()是一个方法，不要忘记括号'''
        news_dict_list.append(news.to_dict())
    data = {
        'news_list': news_dict_list,
        "total_page": total_page,
        "current_page": current_page,
    }
    # if not news:
    #     return jsonify(errno=RET.DATAERR,errmsg="该用户还没有发布过新闻")
    # news_list=[]
    # for nw in news:
    #     news_list.append(nw.to_dict())
    # data = {
    #     'news_list': news_list
    # }
    return render_template("news/user_news_list.html", data=data)